package top.hmtools.wxmp.server.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import top.hmtools.wxmp.AppId;
import top.hmtools.wxmp.core.WxmpSession;
import top.hmtools.wxmp.core.WxmpSessionFactory;
import top.hmtools.wxmp.core.WxmpSessionFactoryBuilder;
import top.hmtools.wxmp.core.access_handle.DefaultAccessTokenHandle;
import top.hmtools.wxmp.core.configuration.AppIdSecretBox;
import top.hmtools.wxmp.core.configuration.AppIdSecretPair;
import top.hmtools.wxmp.core.configuration.WxmpConfiguration;
import top.hmtools.wxmp.webpage.apis.IJsSdkApi;
import top.hmtools.wxmp.webpage.jsSdk.JsSdkTools;

@Configuration
public class DemoConfiguration {

	@Bean
	public WxmpConfiguration wxmpConfiguration() {
		WxmpConfiguration configuration = new WxmpConfiguration();
		return configuration;
	}

	/**
	 * 获取对接微信公众号api接口的会话session
	 * 
	 * @return
	 */
	@Bean
	public WxmpSession wxmpSession(WxmpConfiguration configuration) {

		// 设置 存储appid，appsecret 数据对 的盒子
		AppIdSecretBox appIdSecretBox = new AppIdSecretBox() {

			@Override
			public AppIdSecretPair getAppIdSecretPair() {
				AppIdSecretPair appIdSecretPair = new AppIdSecretPair();
				appIdSecretPair.setAppid(AppId.appid);
				appIdSecretPair.setAppsecret(AppId.appsecret);
				return appIdSecretPair;
			}
		};

		// 设置 获取access token 的中间件
		DefaultAccessTokenHandle accessTokenHandle = new DefaultAccessTokenHandle(appIdSecretBox);
		configuration.setAccessTokenHandle(accessTokenHandle);

		WxmpSessionFactory factory = WxmpSessionFactoryBuilder.build(configuration);
		WxmpSession wxmpSession = factory.openSession();
		return wxmpSession;
	}

	/**
	 * 获取对接微信公众号js-sdk ticket接口的mapper
	 * 
	 * @param wxmpSession
	 * @return
	 */
	@Bean
	public IJsSdkApi JsSdkApi(WxmpSession wxmpSession) {
		return wxmpSession.getMapper(IJsSdkApi.class);
	}

	/**
	 * 获取 js-sdk工具对象实例
	 * 
	 * @param jsSdkApi
	 * @return
	 */
	@Bean
	public JsSdkTools jsSdkTools(IJsSdkApi jsSdkApi,WxmpConfiguration configuration) {
		JsSdkTools jsSdkTools = new JsSdkTools();
		jsSdkTools.setJsSdkApi(jsSdkApi);// 用于有效时间内更新ticket
		jsSdkTools.setWxmpConfiguration(configuration);
		return jsSdkTools;
	}

}
